package com.hongyi.modelcontest.modular.contest.controller;

import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hongyi.modelcontest.core.common.annotion.Permission;
import com.hongyi.modelcontest.core.common.exception.BizExceptionEnum;
import com.hongyi.modelcontest.core.common.page.LayuiPageFactory;
import com.hongyi.modelcontest.modular.contest.service.RecordService;
import com.hongyi.modelcontest.modular.contest.vo.ContestRegister;
import com.hongyi.modelcontest.modular.system.entity.User;
import com.hongyi.modelcontest.modular.system.service.UserService;
import lombok.extern.log4j.Log4j;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

@Controller
@RequestMapping("/record")
@Log4j
public class RecordController {

    private static final String PREFIX = "/modular/contest/record/";

    @Resource
    private RecordService recordService;
    @Resource
    private UserService userService;

    /**
     * 跳转到赛事管理首页
     */
    @RequestMapping("")
    @Permission
    public String index() {
        return PREFIX + "record.html";
    }

    @RequestMapping(value = "/list")
    @Permission
    @ResponseBody
    public Object list(@RequestParam(name = "conditions", required = false) String conditions) {
        IPage list = this.recordService.list(conditions);
        return LayuiPageFactory.createPageInfo(list);
    }

    @RequestMapping(value = "/excel")
    @Permission
    public void excel(@RequestParam(name = "conditions", required = false) String conditions,
                      HttpServletResponse response) {
        this.recordService.excel(conditions, response);
    }

    @RequestMapping("/record_add")
    public String addIndex() {
        return PREFIX + "record_add.html";
    }

    /**
     * 报名
     */
    @PostMapping("/add")
    @ResponseBody
    public ResponseData add(@Valid ContestRegister contestRegister, BindingResult result) {
        if (result.hasErrors()) {
            log.error("数据错误:" + result.toString());
            throw new ServiceException(BizExceptionEnum.REQUEST_INVALID_PARAMETER);
        }
        User user = userService.getById(contestRegister.getAgentId());
        if (user == null) {
            contestRegister.setAgentId("-1");
        }
        return ResponseData.success(recordService.register(contestRegister));
    }
}
